package com.ly.mpayment.rest.up.yunchuang;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.core.util.HttpClient;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("yunchuang")
public class YunChuangRest {

    Logger logger = Logger.getLogger(YunChuangRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @SuppressWarnings("static-access")
    @Path("callBack")
    @POST
    public String callBack(String data) {
        logger.info("yunchuang_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            //{"user_ordernum":"2c922ab9804783880180479be80b029b","order_number":"8A49C6AD5782D92B48805C0D99024F78","order_status":"-1","mobile":"15161873056","ctime":"1650468841","voucher":null,"sign":"9D49739D11D177F8E281A9DD3A862774"}
            JSONObject jsonD = JSONObject.parseObject(data);
            UpOrder order = upOrderService.findById(jsonD.getString("user_ordernum"));
            if (order != null && jsonD.getString("order_status").equals("2") && order.getStatus() == Config.status[0]) {
                order.setRemark(jsonD.containsKey("voucher") ? jsonD.getString("voucher") : jsonD.getString("msg") );
                RechargeRest.successUpOrder.add(order);
                return "success";
            } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("order_status").equals("-1")) {
                order.setRemark(jsonD.getString("msg"));
                RechargeRest.failtUpOrder.add(order);
                return "success";
            } else {
                logger.info("yunchuang_not_found_order:" + jsonD.getString("user_ordernum") + ",");
            }
        }
        return "fail";
    }


    /**
     * 订单提交
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = new JSONObject();
        data.put("account", shop.getAppId());
        data.put("flowCode", order.getUpShopPro().getProductCode());
        data.put("mobile",order.getUpphonenum());
        data.put("orderNumber", order.getUporderuuid());
        data.put("callbackURL", shop.getOrderCallAddress());
        data.put("price", BigUtil.getBigDecimal(order.getDiscountAmount().toString(),4));
        //大写( md5( md5(密码)+手机号码+产品编码+商户订单号+秘钥 ) )
        data.put("sign", MD5.md5(MD5.md5(shop.getUser().getRemark())+order.getUpphonenum()+order.getUpShopPro().getProductCode()
        +order.getUporderuuid()+shop.getUpkey()).toUpperCase());
        String result = HttpClient.httpGetUrl(shop.getOrderCommitAddress().concat("?")+StringSort.jsonToString(data));
        logger.info("commitOrder_yunchuang:"+result+","+data.toString());
        if (!StringUtils.isBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("code") && json.getString("code").equals("2000")) {
                this.upOrderService.updateUpOrderMsg(order,json.getString("order_number"),json.getString("msg"));
            } else if(json.containsKey("code") && errorCode.contains(json.getString("code"))) {
                order.setRemark(json.getString("msg"));
                RechargeRest.failtUpOrder.add(order);
            }
        } else {
            this.upOrderService.updateUpOrderMsg(order, "","提单失败");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    /**
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("5001");
        add("5005");
        add("5002");
        add("5003");
        add("5004");
        add("5006");
        add("5008");
        add("5010");
        add("5101");
        add("5102");
        add("5103");
        add("5104");
        add("5105");
        add("5106");
        add("5107");
        add("5108");
        add("5109");
        add("5201");
        add("5202");
        add("5203");
        add("5301");
        add("5302");
        add("5303");
        add("5304");
        add("5305");
    }};

    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("account", shopInfo.getAppId());
        data.put("user_ordernum", upOrder.getUporderuuid());
        //大写( md5( md5(密码)+ 商户订单号/平台订单号+秘钥 ) )
        data.put("sign", MD5.md5(MD5.md5(shopInfo.getUser().getRemark())
                +upOrder.getUporderuuid()+shopInfo.getUpkey()).toUpperCase());
        String result =  HttpClient.httpGetUrl(shopInfo.getOrderStatusAddress().concat("?")+StringSort.jsonToString(data));
        logger.info("yunchuangqueryOrder:"+upOrder.getUpphonenum()+":"+result);
        if (!StringUtils.isBlank(result)) {
            JSONObject jsonD = JSONObject.parseObject(result);
            UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
            if(jsonD.getString("code").equals("2000")){
                if (order != null && jsonD.getJSONObject("data").getString("order_status").equals("2") && order.getStatus() == Config.status[0]) {
                    order.setRemark(jsonD.containsKey("voucher") ? jsonD.getString("voucher") : jsonD.getString("msg"));
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0]
                        && jsonD.getJSONObject("data").getString("order_status").equals("-1")) {
                    order.setRemark(jsonD.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    logger.info("yunchuang_not_found_order:" + jsonD.toString() + "," + order.getUpphonenum());
                }
            }
        }
    }

}
